package com.davy.tx;


import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import androidx.appcompat.app.AppCompatActivity;

import com.davy.tx.utils.LogUtils;
import com.davy.tx.utils.NetworkChangeReceiver;

import java.util.ArrayList;


public abstract class BaseActivity extends AppCompatActivity {
    protected Context mContext;
    protected boolean isConnected;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        try {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        } catch (Exception e) {
        }
        return super.onTouchEvent(event);
    }

    private void initStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    protected void hideSoftKeyboard() {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
    }


    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 设置只竖屏显示
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        mContext = this;
        initStatusBar();
        hideSoftKeyboard();
        requestPermissions(99);
        ScreenManager.getScreenManager().addActivity(this);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(networkChangeReceiver, intentFilter);
    }

    NetworkChangeReceiver networkChangeReceiver = new NetworkChangeReceiver(isConnected -> {
        LogUtils.e("TAG", "isConnected:" + isConnected);
        network(isConnected);

    });

    protected void network(boolean isConnect) {
        isConnected = isConnect;
    }

    // 请求权限
    public void requestPermissions(int requestCode) {
        try {
            if (Build.VERSION.SDK_INT >= 23) {
                ArrayList<String> requestPerssionArr = new ArrayList<>();
                int hasInternet = checkSelfPermission(Manifest.permission.INTERNET);
                if (hasInternet != PERMISSION_GRANTED) {
                    requestPerssionArr.add(Manifest.permission.INTERNET);
                }
                int camera = checkSelfPermission(Manifest.permission.CAMERA);
                if (camera != PERMISSION_GRANTED) {
                    requestPerssionArr.add(Manifest.permission.CAMERA);
                }
                int write_external_storages = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                if (write_external_storages != PERMISSION_GRANTED) {
                    requestPerssionArr.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                }
                int read_external_storages = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
                if (read_external_storages != PERMISSION_GRANTED) {
                    requestPerssionArr.add(READ_EXTERNAL_STORAGE);
                }
                int access_fine_location = checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION);
                if (access_fine_location != PERMISSION_GRANTED) {
                    requestPerssionArr.add(Manifest.permission.ACCESS_FINE_LOCATION);
                }
                int record_audio = checkSelfPermission(Manifest.permission.RECORD_AUDIO);
                if (record_audio != PERMISSION_GRANTED) {
                    requestPerssionArr.add(Manifest.permission.RECORD_AUDIO);
                }
                int read_phone_state = checkSelfPermission(Manifest.permission.READ_PHONE_STATE);
                if (read_phone_state != PERMISSION_GRANTED) {
                    requestPerssionArr.add(Manifest.permission.READ_PHONE_STATE);
                }
                // 是否应该显示权限请求
                if (requestPerssionArr.size() >= 1) {
                    String[] requestArray = new String[requestPerssionArr.size()];
                    for (int i = 0; i < requestArray.length; i++) {
                        requestArray[i] = requestPerssionArr.get(i);
                    }
                    requestPermissions(requestArray, requestCode);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean flag = false;
        for (int i = 0; i < permissions.length; i++) {
            if (PERMISSION_GRANTED == grantResults[i]) {
                flag = true;
            }
        }
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(networkChangeReceiver);
        super.onDestroy();
    }

    // 隐藏软键盘
    protected void hideSoftInput(IBinder token) {
        if (token != null) {
            InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            manager.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 重写 getResource 方法，防止系统字体影响
     */
    @Override
    public Resources getResources() {//禁止app字体大小跟随系统字体大小调节
        Resources resources = super.getResources();
        Configuration configuration = new Configuration();
        configuration.setToDefaults();
        resources.updateConfiguration(configuration, resources.getDisplayMetrics());
        return resources;
    }
}
